<template>
  <div class="order-report">
    <ArtTableHeader
      title="订单报表"
      :total="tableData.total"
      @refresh="handleRefresh"
    >
      <template #search>
        <OrderReportSearch @search="handleSearch" @reset="handleReset" />
      </template>

      <template #extra>
        <ElButton type="success" @click="handleExport">
          <ElIcon><Download /></ElIcon>
          导出报表
        </ElButton>
      </template>
    </ArtTableHeader>

    <!-- 统计卡片 -->
    <div class="report-summary">
      <ElRow :gutter="20">
        <ElCol :span="6">
          <ElCard>
            <div class="summary-item">
              <div class="summary-value">{{ summaryData.totalOrders }}</div>
              <div class="summary-label">总订单数</div>
            </div>
          </ElCard>
        </ElCol>
        <ElCol :span="6">
          <ElCard>
            <div class="summary-item">
              <div class="summary-value">{{ summaryData.completedOrders }}</div>
              <div class="summary-label">已完成订单</div>
            </div>
          </ElCard>
        </ElCol>
        <ElCol :span="6">
          <ElCard>
            <div class="summary-item">
              <div class="summary-value">{{ summaryData.pendingOrders }}</div>
              <div class="summary-label">待处理订单</div>
            </div>
          </ElCard>
        </ElCol>
        <ElCol :span="6">
          <ElCard>
            <div class="summary-item">
              <div class="summary-value">{{ summaryData.totalQuantity }}</div>
              <div class="summary-label">总处理数量</div>
            </div>
          </ElCard>
        </ElCol>
      </ElRow>
    </div>

    <ArtTable
      :columns="columns"
      :data="tableData.list"
      :loading="tableLoading"
      :pagination="pagination"
      @page-change="handlePageChange"
    >
      <template #orderType="{ row }">
        <ElTag :type="getOrderTypeTag(row.orderType)">
          {{ getOrderTypeText(row.orderType) }}
        </ElTag>
      </template>

      <template #status="{ row }">
        <ElTag :type="getStatusTag(row.status)">
          {{ getStatusText(row.status) }}
        </ElTag>
      </template>

      <template #warehouseName="{ row }">
        <span>{{ getWarehouseName(row.warehouseId) }}</span>
      </template>
    </ArtTable>

    <!-- 统计图表 -->
    <div class="report-charts">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElCard title="订单类型分布">
            <div ref="orderTypeChartRef" style="height: 300px"></div>
          </ElCard>
        </ElCol>
        <ElCol :span="12">
          <ElCard title="订单趋势">
            <div ref="orderTrendChartRef" style="height: 300px"></div>
          </ElCard>
        </ElCol>
      </ElRow>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Download } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useTable } from "@/composables/useTable";
import { useWmsStore } from "@/store/modules/wms";
import OrderReportSearch from "./components/OrderReportSearch.vue";
import type { WMS } from "@/types/wms";

defineOptions({ name: "OrderReport" });

// 使用WMS store
const wmsStore = useWmsStore();

// 表格配置
const columns = [
  { prop: "orderNo", label: "订单号", width: 150 },
  { prop: "orderType", label: "订单类型", width: 100, slot: "orderType" },
  { prop: "warehouseName", label: "仓库", width: 120, slot: "warehouseName" },
  { prop: "merchantName", label: "商户", width: 150 },
  { prop: "totalQuantity", label: "总数量", width: 100 },
  { prop: "status", label: "状态", width: 100, slot: "status" },
  { prop: "createTime", label: "创建时间", width: 160 },
  { prop: "updateTime", label: "更新时间", width: 160 },
];

// 统计数据
const summaryData = reactive({
  totalOrders: 0,
  completedOrders: 0,
  pendingOrders: 0,
  totalQuantity: 0,
});

// 模拟API调用
const fetchOrderReport = async (params: any) => {
  return new Promise<{ list: any[]; total: number }>((resolve) => {
    setTimeout(() => {
      const mockData = Array.from({ length: 20 }, (_, index) => ({
        id: index + 1,
        orderNo: `ORD${String(index + 1).padStart(6, "0")}`,
        orderType: ["1", "2", "3", "4"][Math.floor(Math.random() * 4)],
        warehouseId: 1,
        merchantName: `商户${index + 1}`,
        totalQuantity: Math.floor(Math.random() * 1000),
        status: ["1", "2", "3", "4"][Math.floor(Math.random() * 4)],
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString(),
      }));

      // 更新统计数据
      summaryData.totalOrders = 150;
      summaryData.completedOrders = 120;
      summaryData.pendingOrders = 30;
      summaryData.totalQuantity = 15000;

      resolve({
        list: mockData,
        total: 150,
      });
    }, 1000);
  });
};

// 使用表格组合式函数
const { tableData, tableLoading, pagination, handlePageChange, refreshTable } =
  useTable({
    fetchData: fetchOrderReport,
    defaultPageSize: 20,
  });

// 搜索参数
const searchParams = ref<any>({});

// 图表引用
const orderTypeChartRef = ref();
const orderTrendChartRef = ref();

// 获取仓库名称
const getWarehouseName = (warehouseId: number) => {
  const warehouse = wmsStore.warehouseMap[warehouseId];
  return warehouse?.warehouseName || "-";
};

// 获取订单类型标签
const getOrderTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    "1": "success",
    "2": "warning",
    "3": "info",
    "4": "primary",
  };
  return typeMap[type] || "info";
};

// 获取订单类型文本
const getOrderTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    "1": "入库单",
    "2": "出库单",
    "3": "移库单",
    "4": "盘点单",
  };
  return typeMap[type] || "未知";
};

// 获取状态标签
const getStatusTag = (status: string) => {
  const statusMap: Record<string, string> = {
    "0": "info",
    "1": "warning",
    "2": "primary",
    "3": "success",
    "4": "danger",
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    "0": "草稿",
    "1": "待处理",
    "2": "处理中",
    "3": "已完成",
    "4": "已取消",
  };
  return statusMap[status] || "未知";
};

// 搜索处理
const handleSearch = (params: any) => {
  searchParams.value = params;
  refreshTable(params);
};

// 重置搜索
const handleReset = () => {
  searchParams.value = {};
  refreshTable();
};

// 刷新
const handleRefresh = () => {
  refreshTable(searchParams.value);
};

// 导出报表
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 初始化图表
const initCharts = () => {
  console.log("初始化订单报表图表...");
};

// 初始化
onMounted(async () => {
  // 加载基础数据
  await wmsStore.getWarehouseList();

  // 加载表格数据
  refreshTable();

  // 初始化图表
  initCharts();
});
</script>

<style lang="scss" scoped>
.order-report {
  padding: 20px;

  .report-summary {
    margin-bottom: 20px;

    .summary-item {
      text-align: center;

      .summary-value {
        font-size: 24px;
        font-weight: bold;
        color: var(--el-color-primary);
        margin-bottom: 8px;
      }

      .summary-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
    }
  }

  .report-charts {
    margin-top: 20px;
  }

  :deep(.art-table-header) {
    margin-bottom: 16px;
  }
}
</style>
